package controllers

import (
	"blog-server/app/common/response"
	"blog-server/utils"
	"github.com/gin-gonic/gin"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"time"
)

// UploadFile 上传文件
func UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		response.BusinessFail(c, "系统错误")
		return
	}
	ext := path.Ext(file.Filename)
	fileNameInt := time.Now().Unix()
	fileNameStr := strconv.FormatInt(fileNameInt, 10)
	fileName := fileNameStr + ext
	filePath := filepath.Join(utils.Mkdir("public"), "/", fileName)
	re := regexp.MustCompile("\\\\")
	replacedPath := re.ReplaceAllString(filePath, "/")
	c.SaveUploadedFile(file, filePath)
	resPath := "/" + replacedPath
	response.Success(c, resPath)
}
